package com.peng.sort.merge;

import com.peng.utils.TestUtils;

import java.util.Arrays;

/*

在一个数组中，
对于每个数num，求有多少个后面的数 * 2 依然<num，求总个数
比如：[3,1,7,0,2]
3的后面有：1，0
1的后面有：0
7的后面有：0，2
0的后面没有
2的后面没有
所以总共有5个
 */
public class Test03_DoubleAfterLessNumCount {

    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 100;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr1 = TestUtils.generateRandomArray(maxSize, maxValue);
            int[] arr2 = TestUtils.copyArray(arr1);
            try {
                if (getDoubleAfterLessNumCount(arr1) != getDoubleAfterLessNumCountEasy(arr2)) {
                    succeed = false;
                    TestUtils.printArray(arr1);
                    TestUtils.printArray(arr2);
                    break;
                }
            } catch (Exception e) {
                System.out.println(Arrays.toString(arr1));
            }
        }
        System.out.println(succeed ? "Nice!" : "Fucking fucked!");

    }

    //对数器
    public static int getDoubleAfterLessNumCountEasy(int[] arr) {
        int res = 0;
        for (int i = 1; i < arr.length; i++) {
            for (int j = 0; j < i; j++) {
                res += arr[i] * 2 < arr[j] ? 1 : 0;
            }
        }
        return res;
    }

    public static int getDoubleAfterLessNumCount(int[] arr) {
        if (arr == null || arr.length < 2) {
            return 0;
        }
        return getDoubleAfterLessNumCount(arr, 0, arr.length - 1);
    }

    private static int getDoubleAfterLessNumCount(int[] arr, int L, int R) {
        if (L == R) {
            return 0;
        }
        int mid = L + ((R - L) >> 1);

        return getDoubleAfterLessNumCount(arr, L, mid)
                + getDoubleAfterLessNumCount(arr, mid + 1, R)
                + merge(arr, L, mid, R);
    }

    private static int merge(int[] arr, int L, int mid, int R) {
        int p1 = L;
        int p2 = mid + 1;
        int[] help = new int[R - L + 1];
        int i = 0;

        int res = 0;

        int windowR = mid + 1;
        for (int m = L; m <= mid; m++) {
            while (windowR <= R && arr[windowR] * 2 < arr[m]) {
                windowR++;
            }
            res += windowR - mid - 1;
        }
//利用归并排序的特征：
// 1、左右两组各自有序
// 2、左右两边小组逐渐merge成越来越大的大组
// 从而整个累加过程，可以实现指针不回退，一直向前

        while (p1 <= mid && p2 <= R) {
            if (arr[p1] < arr[p2]) {
                help[i++] = arr[p1++];
            } else {
                help[i++] = arr[p2++];
            }
        }

        while (p1 <= mid) {
            help[i++] = arr[p1++];
        }
        while (p2 <= R) {
            help[i++] = arr[p2++];
        }


        for (int m = 0; m < help.length; m++) {
            arr[L + m] = help[m];
        }

        return res;
    }
}
